/**
 * Created with IntelliJ IDEA.
 * Description:两个链表的第一个·共同节点
 * User: wangxin
 * Date: 2024-10-23
 * Time: 22:48
 */
import java.util.*;
public class test {


    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
   //解法一
        public ListNode FindFirstCommonNode1(ListNode pHead1, ListNode pHead2){
            if(pHead1 == null||pHead2 == null){
                return null;
            }
            ListNode cur1 = pHead1;
            ListNode cur2 = pHead2;
            int c1 = 0,c2 = 0;
            while(cur1 != null){
                cur1 = cur1.next;
                c1++;
            }
            while(cur2 != null){
                cur2 = cur2.next;
                c2++;
            }
            int c ;
            if(c1 > c2){
                c = c1 - c2;
                for(int i = 0;i < c;i++){
                    pHead1 = pHead1.next;
                }
            }else{
                c = c2 - c1;
                for(int i = 0;i < c;i++){
                    pHead2 = pHead2.next;
                }
            }
            while(pHead1 != null&&pHead2 != null){
                if(pHead1 == pHead2){
                    return pHead1;
                }
                pHead1 = pHead1.next;
                pHead2 = pHead2.next;
            }
            return null;

        }
    //解法二
    public ListNode FindFirstCommonNode2(ListNode pHead1, ListNode pHead2) {
        ListNode l1 = pHead1, l2 = pHead2;
        while(l1 != l2){
            l1 = (l1==null)?pHead2:l1.next;
            l2 = (l2==null)?pHead1:l2.next;
        }
        return l1;
    }

}
